/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-03-19 11:41:39
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-04-06 12:09:38
 * @Description: file content
 */

import { FuncController as Controller } from "../../../libs/controller/Common";
import * as uuid from "uuid";
import * as path from "path";
import * as fs from "fs";
import streamwormhole from "stream-wormhole";
import * as moment from "moment";

import { mkdirs } from "@diyaner/dy-utils/libs/node/files";
import { FileStream } from "egg";

export default class SysLogController extends Controller {
  model = this.app.model.Sys.Oss;

  async getSearchData() {
    const page: [number, number] = this.ctx.request.body.page || [20, 0];
    const searchs: {
      method: string;
    } = this.ctx.request.body.searchs;

    let wheres = {} as any;
    if (searchs) {
      wheres = searchs;
    }
    // console.log(searchs);
    const data = await this.app.model.Sys.Oss.findAndCountAll({
      raw: false,
      limit: page[0],
      offset: page[1],
      order: [["createdAt", "desc"]],
      where: {
        ...wheres,
      },
      attributes: {
        include: [
          [
            this.app.model.Sequelize.col("create_user.user_name"),
            "create_user_name",
          ],
        ],
      } as any,
      include: {
        model: this.app.model.Sys.User,
        as: "create_user",
        attributes: [],
      },
    });
    this.ctx.success(data);
  }

  private async waitWriteStream(
    uploadStream: FileStream,
    writeStream: fs.WriteStream
  ) {
    return new Promise((resolve, reject) => {
      try {
        uploadStream.pipe(writeStream);

        uploadStream.on("end", () => {
          // console.log("end");
          writeStream.end();
          // writeStream.close();
          resolve(true);
        });
      } catch (error) {
        // 若发生错误，将上传文件流消费掉。
        streamwormhole(uploadStream);
        reject(error);
      }
    });
  }

  /** 创建按月份的文件夹，并返回其路径，上传的文件按月份归档。 */
  private createDir(saveDir: string) {
    if (!fs.existsSync(saveDir)) {
      mkdirs(saveDir);
    }
    return saveDir;
  }
  /** 上传文件接口 */
  async upload() {
    const ctx = this.ctx;
    const uploadStream = await ctx.getFileStream();
    const fileExtension = path
      .extname(uploadStream.filename)
      .toLocaleLowerCase();
    // console.log(originName);
    let name = uuid.v4() + fileExtension;
    const currentMonth = moment().format("YYYYMM");

    const localOssConfig = await this.ctx.service.sys.config.getConfigObject();
    // 上传文件保存的路径
    let saveDir = localOssConfig.oss?.local?.dir || "D:/uploads";
    saveDir = this.createDir(saveDir);

    const writeFile = path.resolve(saveDir, currentMonth, name);
    // let result;
    const writeStream = fs.createWriteStream(writeFile);
    await this.waitWriteStream(uploadStream, writeStream);
    // 拼接文件的访问链接。
    let prefix: string =
      localOssConfig.oss?.local?.url || "http://localhost:7001/";
    // console.log(localOssConfig.oss?.local?.url);
    if (prefix.charAt(prefix.length - 1) !== "/") prefix += "/";

    const file_db_row = await this.model.create({
      url: prefix + currentMonth + "/" + name,
      create_user_id: this.ctx.loginUserInfo.uid,
    });
    ctx.success(file_db_row.toJSON());
  }

  /** 获取本地oss的文件 */
  async getLocalOssFile() {
    const params = this.ctx.params;
    const localOssConfig = await this.ctx.service.sys.config.getConfigObject();
    let file_path: string = localOssConfig.oss?.local?.dir || "D:/uploads";
    if (file_path.charAt(file_path.length - 1) !== "/") file_path += "/";
    file_path += params.month + "/" + params.fileName;
    if (fs.existsSync(file_path)) {
      // console.log("is exist.");
      this.ctx.set("Content-Type", "application/octet-stream");
      this.ctx.attachment(file_path);
      // const fileObj = fs.readFileSync(file_path);
      this.ctx.body = fs.createReadStream(file_path);
    } else {
      this.ctx.body = "";
    }
  }

  a() {}
}
